package com.yxjme.redrainapp;

import android.app.Activity;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import com.yxjme.redrainlibrary.a.WindowManagerPermission;

public class RedPacketRainWindowManager {


    private View view;
    private Activity activity;
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mLayoutParams;
    private static RedPacketRainWindowManager manager;


    public static RedPacketRainWindowManager newInstance(Activity activity){
        if (null == manager){
            synchronized (RedPacketRainWindowManager.class){
                if (null == manager){
                    manager = new RedPacketRainWindowManager(activity);
                }
            }
        }
        return manager ;
    }


    private RedPacketRainWindowManager(Activity activity){
         this.activity=activity;
         mWindowManager = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
         init();
    }



    private void init() {
        mLayoutParams = new WindowManager.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT,
                0,
                0,
                PixelFormat.TRANSPARENT);
        mLayoutParams.flags =
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
                        WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
                        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED;

        if(Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1){
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE | WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        }else {
            mLayoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }

        mLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
        mLayoutParams.x = 0;
        mLayoutParams.y = 0;
    }





    /**
     * 设置显示view
     *
     * @param view
     */
    public void setContentView(View view){
        this.view=view ;
    }



    /**
     *  显示  悬浮的视图
     */
    public void show(){
        if (WindowManagerPermission.checkFloatPermission(activity)){
            if (view!=null&&mLayoutParams!=null)
                mWindowManager.addView(view, mLayoutParams);
        }else {
            WindowManagerPermission.goToOpenPermission(activity);
        }
    }


    /**
     * 关闭悬浮
     */
    public void dismiss(){
        if (view!=null) mWindowManager.removeViewImmediate(view);
    }


    /**
     * 获得焦点
     */
    public void resume(){
        if (view!=null)
            view.setVisibility(View.VISIBLE);
    }



    /**
     * 失去焦点
     */
    public void pause(){
        if (view!=null)
            view.setVisibility(View.GONE);
    }


}
